package m.jclecai.com.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

import m.jclecai.com.contents.LotteryType;
import m.jclecai.com.listener.Callback;

/**
 * Created by hp on 2017/3/16.
 */

public class BaseUtils {
    /**
     * 获取屏幕尺寸
     */
    public static int getDisplaySize(Context context, String direction) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (direction.equals("width")) {
            int width = wm.getDefaultDisplay().getWidth();
            return width;
        } else if (direction.equals("height")) {
            int height = wm.getDefaultDisplay().getHeight();
            return height;
        }
        return 0;
    }

    public static int[] measureView(final View view) {
        final int[] width = new int[1];
        ViewTreeObserver vto2 = view.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                width[0] = view.getWidth();
            }
        });
        return width;
    }

    /**
     * 固执器：计算差值的一个方法；
     * @param fraction
     * @param startValue
     * @param endValue
     * @return
     */
    public static Float evaluate(float fraction, Number startValue, Number endValue) {
        float startFloat = startValue.floatValue();
        return startFloat + fraction * (endValue.floatValue() - startFloat);
    }



    /**
     * 获取状态栏高度——方法1
     */

    public static int getStatusHeight(Context context) {
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }



    /***
     * @param paramInt1
     * @param paramInt2
     * @return 计算金额
     */
    public static int math1(int paramInt1, int paramInt2) {
        int i;
        if (paramInt1 == paramInt2)
            i = 1;
        while (true) {
            i = paramInt1;
            while (paramInt1 != paramInt2) {
                i *= (paramInt1 - 1);
                paramInt1--;
            }
            return i;
        }
    }

    /**
     * 这个是任选几的算法，
     * @param paramInt1 已经选择了多少，
     * @param paramInt2 需要选择多少个
     * @return 如果是需要选择是一个的话， 选择了多少就是多少注，如果不是的话，就会有相应的算法；
     */
    public static int math2(int paramInt1, int paramInt2) {
        if (paramInt2 == 1) {
            return paramInt1;
        } else {
            return math1(paramInt2, 1)==0? 0:math1(paramInt1, 1 + (paramInt1 - paramInt2)) / math1(paramInt2, 1);
        }
    }

    /***
     * 获取当前系统时间
     */
    public static String getCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /***
     * 比较时间差值
     */
    public static long contrastDate(String d, String t, int tag) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date now = null;
        try {
            now = df.parse(d);
            java.util.Date date = df.parse(t);
            long l = now.getTime() - date.getTime();
            long day = l / (24 * 60 * 60 * 1000);
            long hour = (l / (60 * 60 * 1000) - day * 24);
            long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            switch (tag) {
                case 0:
                    return day;
                case 1:
                    return hour;
                case 2:
                    return min;
                case 3:
                    return s;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
        return 0;
    }


    /***
     * 格式化时间
     *
     * @param date
     * @return
     */
    public static String formatDate(long date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd- HH:mm:ss");
        Date curDate = new Date(date);//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /***
     * 格式化时间返回分钟
     *
     * @return
     */
    public static String formatDateMinute(long date) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        Date curDate = new Date(date);//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 这里最多只能容纳24小时超过的话就会有问题；
     * 格式化时间返回，1000*10 返回为 00：10；
     * 1000*60*60+1000*60*5   01:05:00;
     * @param
     * @return 返回时间对应的字符串；
     */
    public static String formatDateLineToString(long date){
        //这里的话， 我们对毫秒进行一个格式化的操作；
        long hours=0;
        long seconds = date / 1000;
        long minutes = seconds / 60;
        long second = seconds % 60;

        if (minutes>=60) {
            hours=minutes/60;
            minutes=minutes%60;
        }
        String time="";
        if(hours==0){
            //这里表示没有小时；
            time+=formatNumberToString(minutes);
            time+=":"+formatNumberToString(second);

        }else {
            //这里表示有小时的字符串拼接；
            time+=formatNumberToString(hours);
            time+=":"+formatNumberToString(minutes);
            time+=":"+formatNumberToString(second);
        }
        return time;
    }


    /**
     * 这里我们是对大于0的number进行一个格式化；
     * @param number 需要格式化的数字
     * @return 小于10的，在前面+0，否则原样子返回；
     */
    public static String formatNumberToString(long number){
        String time="";
        if(number<10){
            time+="0"+number;
        }else{
            time+=number;
        }
        return time;
    }


    //String状态转Int
    public static int stringOfInt(String type) {
        if (type.equals("sdsyxw")) {
            return LotteryType.SDXYXW;
        } else if (type.equals("syxw")) {
            return LotteryType.SYXW;
        } else if (type.equals("dlt")) {
            return LotteryType.DLT;
        } else if (type.equals("ssq")) {
            return LotteryType.SSQ;
        } else if (type.equals("qlc")) {
            return LotteryType.QLC;
        } else if (type.equals("qxc")) {
            return LotteryType.QXC;
        } else if (type.equals("pls")) {
            return LotteryType.PLS;
        } else if (type.equals("plw")) {
            return LotteryType.PLW;
        } else if (type.equals("sd")) {
            return LotteryType.SD;
        } else if (type.equals("cqssc")) {
            return LotteryType.CQSSC;
        } else if (type.equals("jsks")) {
            return LotteryType.JSKS;
        }else if(type.equals("klpk")){
            return LotteryType.KLPK;
        }else if(type.equals("zjsyxw")){
            return LotteryType.ZJSYXW;
        }else if(type.equals("jssyxw")){
            return LotteryType.JSSYXW;
        }
        else {
            return 0;
        }

    }


    /**
     * @param mobiles
     * @return 验证手机号格式
     */
    public static boolean
    isMobileNO(String mobiles) {

        String telRegex = "[1][3456789]\\d{9}";
        if (TextUtils.isEmpty(mobiles))//
            return false;
        else
            return mobiles.matches(telRegex);
    }

    /**
     * 开启一个Activity
     *
     * @param ctx
     * @param clazz
     */
    public static void startAcy(Context ctx, Class clazz) {
        ctx.startActivity(new Intent(ctx, clazz));
    }

    public static int getByte(String str) {
        byte[] b = null;
        try {
            b = str.getBytes("gbk");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return b.length;
    }

    /**
     * 获取用户当前是否登录
     */
    public static boolean isLogin(Context context) {
        String userName = PreferenceUtil.getUserName(context);
        String password = PreferenceUtil.getPassword(context);
        boolean login_state = PreferenceUtil.isLogin(context);
        if (login_state == false || TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 判断有无网络
     */
    public static boolean netWork(Context context) {
        ConnectivityManager mConnectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
        // 检查网络连接，如果无网络可用，就不需要进行连网操作等
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();
        if (info == null || !mConnectivity.getBackgroundDataSetting()) {
            return false;
        }
        // 判断网络连接类型，只有在3G或wifi里进行一些数据更新。
        int netType = info.getType();
        if (netType == ConnectivityManager.TYPE_WIFI) {
            return info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE) {
            return info.isConnected();
        } else {
            return false;
        }
    }

    public  static  CountDownTimer timer = null;
    /**
     * @param mContext Context
     * @param time     倒计时的时间
     * @param btn      倒计时的控件
     */
    public static void countDowm(final Context mContext, int time,
                                 final TextView btn, final String tvText) {

         timer = new CountDownTimer(time * 600, 1000) {
            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onTick(long millisUntilFinished) {
                btn.setText("还剩" + millisUntilFinished / 600 + "秒");
                btn.setEnabled(false);
            }

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onFinish() {
                btn.setText(tvText);
                btn.setEnabled(true);
            }
        };
        timer.start();
    }

    /**
     * @param mContext Context
     * @param time     倒计时的时间
     * @param btn      倒计时的控件
     */
    public static void countDowm(final Context mContext, int time,
                                 final TextView btn) {
        countDowm(mContext, time, btn, "重新发送");
    }


    /**
     *   关闭定时器
     */
    public static void CannelTimer(final TextView btn, final String tvText){
        if (timer!=null){
            timer.cancel();
            btn.setText(tvText);
            btn.setEnabled(true);
        }
    }

    /**
     * 合买倒计时
     */
    public static void saleEnd(final TextView v, long millisInFuture, long countDownInterval) {
        millisInFuture = millisInFuture - System.currentTimeMillis();
        CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {
            int HH, mm, ss, ms;
            String timeString;

            @Override
            public void onTick(long millisUntilFinished) {
                HH = (int) (millisUntilFinished / 3600000);
                mm = (int) (millisUntilFinished % 3600000 / 60000);
                ss = (int) (millisUntilFinished % 60000 / 1000);
                ms = (int) (millisUntilFinished % 1000 / 100);
                timeString = HH + ":" + mm + ":" + (ss < 10 ? "0" : "") + ss;
                v.setText(timeString);
            }

            @Override
            public void onFinish() {
                v.setText("已截止");
            }
        };
        timer.start();
    }

    public static String formatPhone(String phone) {
        if (phone.length() < 11) return phone;
        phone = phone.substring(0, 3) + "****" + phone.substring(7);
        return phone;
    }

    public static String formatIdCard(String idcard) {
        if(TextUtils.isEmpty(idcard)) return "";
        if (idcard.length() == 15)
            idcard = "**" + idcard.substring(2, 11) + "****";
        if (idcard.length() < 18)
            return idcard;
        idcard = "**" + idcard.substring(2, 14) + "****";
        return idcard;
    }

    public static String strNoNull(String txt) {
        if (TextUtils.isEmpty(txt)) return "";
        return txt;
    }

    public static void startWeChat(Activity activity) {
        try{
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            activity.startActivity(intent);
//            activity.startActivityForResult(intent, 0);
        }catch (Exception e){
//            ToastUtil.showToast(activity,"未安装微信");
        }
    }

    public static float getDecimalMoney(float number){
        return getDecimalMoney(number,0);
    }

    /**
     * 五入
     * @param number
     * @param position 保留小数位
     * @return
     */
    public static float getDecimalMoney(float number,int position){
        BigDecimal bg = new BigDecimal(number).setScale(position, RoundingMode.HALF_UP);
        return bg.floatValue();
    }

    public static float getNumberSum(String[] param){
        float v = 0;
        if(param == null) return v;
        for (String value : param){
            if(!TextUtils.isEmpty(value))
                v += Float.valueOf(value);
        }
        return v;
    }

    /**
     * 向剪切板写入字符串
     */
    public static void setClipString(Context context, String val) {
        ClipboardManager myClipboard = (ClipboardManager)context.getSystemService(
                Context.CLIPBOARD_SERVICE);
        ClipData myClip = ClipData.newPlainText("text", val);
        myClipboard.setPrimaryClip(myClip);
    }

    /**
     * 获取剪切板写入的字符串
     */
    public static String getClipString(Context context) {
        try {
            ClipboardManager myClipboard = (ClipboardManager)context.getSystemService(
                    Context.CLIPBOARD_SERVICE);
            if (myClipboard.hasPrimaryClip()) {
                return myClipboard.getPrimaryClip().getItemAt(0).getText().toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过使用Html返回有颜色的字体
     * @param text
     * @param color
     * @return
     */
    public static Spanned setTextColor(String text, String color){
        String str="<html><font color='"+color+"'></font></html>";
        return Html.fromHtml(str);
    }

    public static int generateViewId() {
        AtomicInteger sNextGeneratedId = new AtomicInteger(1);
        for (;;) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }



    /**
     * 获取期号的定时器
     */
    public static void startTermTimer(long millisInFuture, long countDownInterval, final Callback callback) {
        CountDownTimer timer = new CountDownTimer(millisInFuture, countDownInterval) {

            @Override
            public void onTick(long millisUntilFinished) {
                if(callback != null) callback.onTimerTick(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                if(callback != null) callback.onTimerFinish();
            }
        };
        timer.start();
    }




    /**
     *  String 转 float
     * @param number
     * @param defaultValue
     * @return
     */
    public static float convertToFloat(String number, float defaultValue) {
        if (TextUtils.isEmpty(number)) {
            return defaultValue;
        }
        try {
            return Float.parseFloat(number);
        } catch (Exception e) {
            return defaultValue;
        }

    }


    /**
     * 日期转星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        java.util.Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
}

